import config from '../config'
import Vue from '../instance/index'
import Util from '../util'
import watchArray from '../watchArray'
import Watcher from '../observer/watcher'

export default {

    model: {
        bind(){
            let vm = this.vm,
                key = this.key,
                filters = this.filters;
            new Watcher(vm, this, key, filters, this.update)
            this.element.addEventListener('input', function (e) {
                vm[key] = e.target.value
            })
        },
        update(value){
            this.element.value = value
        }
    },
    text: function (value) {
        this.element.textContent = value || ''
    },
    show: function (value) {
        this.element.style.display = value ? '' : 'none'
    },
    class: function (value) {
        console.log(value)
        console.log(this.arg)
        this.element.classList[value ? 'add' : 'remove'](this.arg);
    },
    for: {
        update(collection){
            this.element.removeAttribute(config.prefix + '-for');
            this.mark = document.createComment(config.prefix + '-for-' + this.key + '-mark');
            let container = this.element.parentNode;
            container.insertBefore(this.mark, this.element);
            container.removeChild(this.element);
            this.childVms = [];

            //todo destory childSeeds

            let forPrefix = this.forPrefix;
            let mutate = function (mutation) {
                console.log(mutation)
            }
            watchArray(collection, mutate.bind(this))
            let self = this;
            collection.forEach(function (val, i) {
                let node = self.element.cloneNode(true);
                let opts = {};
                opts.data = {};
                Util.extend(opts.data, val);
                let forChildComponent = new Vue(node, opts, {
                    forPrefix: forPrefix,
                    parent: self
                });
                container.insertBefore(node, self.mark);
                self.childVms.push(forChildComponent);
                collection[i] = forChildComponent;
            })
        }
    },
    on: {
        update: function (handler) {
            if (handler && this.directiveArg) {
                var self = this,
                    event = this.directiveArg,
                    proxy = function (e) {
                        handler({
                            vm: self.vm,
                            el: e.currentTarget,
                            originalEvent: e,
                            directive: self
                        })
                    }
                this.element.addEventListener(event, proxy);
            }
        },
        unbind: function () {
            var event = this.directiveArg
            if (this.handlers) {
                this.el.removeEventListener(event, this.handlers[event])
            }
        }
    }
}
